import 'dart:typed_data';

import 'package:flutter/foundation.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

const write_service = 'FF00';
const write_uuid = 'FF02';
const read_service = 'FF00';
const read_uuid = 'FF01';

class SendData {
  static List<int> getBytes(String tag, var data) {
    List<int> bytes = [0xDD];
    List<int> cmd = [];
    List<int> length = [];
    List<int> data_bytes = [];
    switch (tag) {
      case '基本信息':
        bytes.add(0xA5);
        cmd = [0x03];
        break;
      case '单体电压':
        bytes.add(0xA5);
        cmd = [0x04];
        break;
      case '硬件版本号':
        bytes.add(0xA5);
        cmd = [0x05];
        break;
      case '保护统计次数':
        bytes.add(0xA5);
        cmd = [0xAA];
        break;
      case '控制指令':
        bytes.add(0x5A);
        cmd = [0x0A];
        data_bytes = (data is List<int>) ? data : List<int>.from(data);
        break;
      case '查询电池':
        bytes.add(0xA5);
        cmd = [0x0A];
        break;
      default:
        break;
    }

    ///拼接命令+数据长度+数据内容
    List<int> check_bytes = [];
    check_bytes += cmd;
    check_bytes += [data_bytes.length];
    check_bytes += data_bytes;

    ///获取校验码
    Uint8List check = crc(check_bytes);
    bytes += check_bytes;
    bytes += check;
    bytes.add(0x77);
    return bytes;
  }

  static Uint8List crc(List<int> data) {
    int checksum = data.fold(0, (prev, element) => prev + element) & 0xFFFF; // 计算校验和
    int invertedChecksum = (~checksum + 1) & 0xFFFF; // 取反加 1
    // return Uint8List.fromList([invertedChecksum]); // 高位在前，低位在后（单字节无需调整）
    return Uint8List.fromList([(invertedChecksum >> 8) & 0xFF, invertedChecksum & 0xFF]); // 高位在前
  }

  static void send(String tag, var data) {
    List<int> bytes = getBytes(tag, data);
    print('自定义的类， 发送数据 = ${bytes.toHexstr(' |')}');
    if (bytes.isEmpty) {
      return;
    }
    // int priority = tag == '查询电池' ? 1 : 0;
    BluetoothManager.instance.write(
        data: bytes, service_uuid: write_service, characteristics_uuid: write_uuid, priority: 0, withoutResponse: true);
  }
}
